<template>
  <div>
    <div class="page-header">
      <h2>业务管理</h2>
      <div>
        <input type="file" accept=".xlsx" @change="importBusinesses" style="display:none" ref="fileInput" />
        <button class="btn" @click="openAdd">新增业务</button>
        <button class="btn" @click="showImportDialog = true">导入</button>
        <button class="btn" @click="exportBusinesses">导出</button>
        <input v-model="search" placeholder="搜索业务" class="search-input" />
      </div>
    </div>
    <table class="data-table">
      <thead>
        <tr>
          <th>业务编号</th>
          <th>业务名称</th>
          <th>业务类型</th>
          <th>业务描述</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in filteredList" :key="item.id">
          <td>{{ item.code }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.type }}</td>
          <td>{{ item.desc }}</td>
          <td class="action-cell">
            <button class="btn" @click="edit(item)">编辑</button>
            <button class="btn" @click="remove(item.id)">删除</button>
          </td>
        </tr>
      </tbody>
    </table>
    <div v-if="showAdd" class="modal">
      <div class="modal-content">
        <h3>{{ editId ? '编辑业务' : '新增业务' }}</h3>
        <input v-model="form.code" placeholder="业务编号" />
        <input v-model="form.name" placeholder="业务名称" />
        <input v-model="form.type" placeholder="业务类型" />
        <input v-model="form.desc" placeholder="业务描述" />
        <div class="modal-actions">
          <button class="btn" @click="save">保存</button>
          <button class="btn" @click="close">取消</button>
        </div>
      </div>
    </div>
    <!-- 依旧选择 -->
    <div v-if="showImportDialog" class="modal">
      <div class="modal-content">
        <h3>请选择导入方式</h3>
        <div style="margin: 20px 0;">
          <button class="btn" @click="handleDirectImport">直接导入</button>
          <button class="btn" @click="downloadTemplate">下载模板再导入（推荐）</button>
        </div>
        <button class="btn" @click="showImportDialog = false">取消</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import * as XLSX from 'xlsx'
   const list = ref([
     { id: 1, code: 'B001', name: '网站建设', type: '开发服务', desc: '企业官网开发' },
     { id: 2, code: 'B002', name: '服务器检查', type: '运维', desc: '定期检查' }
   ])
const search = ref('')
const showAdd = ref(false)
const editId = ref(null)
const form = ref({ name: '', type: '', desc: '' })
const fileInput = ref(null)
const showImportDialog = ref(false)

async function fetchList() {
  console.log('fetchList called')
  const res = await axios.get('http://localhost:8080/api/businesses')
  list.value = res.data.map(item => ({
    id: item.businessid,
    name: item.businessname,
    type: item.businesstype,
    desc: item.businessdesc,
    code: item.businesscode
  }))
}

onMounted(fetchList)

const filteredList = computed(() =>
  list.value.filter(item =>
    item.name.includes(search.value) ||
    item.type.includes(search.value) ||
    item.desc.includes(search.value)
  )
)

function openAdd() {
  editId.value = null
  form.value = { name: '', type: '', desc: '' }
  showAdd.value = true
}
function edit(item) {
  editId.value = item.id
  form.value = { name: item.name, type: item.type, desc: item.desc }
  showAdd.value = true
}
async function remove(id) {
  try{await axios.delete(`http://localhost:8080/api/businesses/${id}`)
  await fetchList()
  }
  catch (e) {
    alert('该业务有关联工单，不能被删除！');
  }
}

async function save() {
  const payload = {
    businesscode: form.value.code,
    businessname: form.value.name,
    businesstype: form.value.type,
    businessdesc: form.value.desc
  }
  if (editId.value) {
    await axios.put(`http://localhost:8080/api/businesses/${editId.value}`, payload)
  } else {
    await axios.post('http://localhost:8080/api/businesses', payload)
  }
  await fetchList()
  close()
}
function close() {
  showAdd.value = false
  editId.value = null
  form.value = { code: '',name: '', type: '', desc: '' }
}
// 导出为Excel
function exportBusinesses() {
  const header = ['业务编号','业务名称', '业务类型', '业务描述'];
  const data = list.value.map(u => [u.code,u.name, u.type, u.desc]);
  const ws = XLSX.utils.aoa_to_sheet([header, ...data]);
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, '业务数据');
  XLSX.writeFile(wb, '业务数据.xlsx');
}
// 触发文件选择
function triggerImport() {
  showImportDialog.value = true;
}
function handleDirectImport() {
  showImportDialog.value = false;
  fileInput.value.click();
}
function downloadTemplate() {
  const header = ['业务编号','业务名称', '业务类型', '业务描述'];
  const ws = XLSX.utils.aoa_to_sheet([header]);
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, '业务模板');
  XLSX.writeFile(wb, '业务导入模板.xlsx');
}
// 导入Excel
async function importBusinesses(e) {
  const file = e.target.files[0];
  if (!file) return;
  const reader = new FileReader();
  reader.onload = async function(evt) {
    const data = new Uint8Array(evt.target.result);
    const workbook = XLSX.read(data, { type: 'array' });
    const sheet = workbook.Sheets[workbook.SheetNames[0]];
    const rows = XLSX.utils.sheet_to_json(sheet, { header: 1 });
    const expectedHeader = ['业务编号','业务名称', '业务类型', '业务描述'];
    const fileHeader = rows[0] || [];
    const isHeaderValid = expectedHeader.every((h, i) => h === fileHeader[i]);
    if (!isHeaderValid) {
      alert('导入失败：表头格式不正确，请使用模板或检查列顺序！');
      return;
    }
    const businesses = rows.slice(1).map((row, idx) => {
      if (row.length < 4 || row.some(cell => cell === undefined || cell === null)) {
        alert(`第${idx + 2}行数据不完整，已跳过`);
        return null;
      }
      return {
        businesscode: row[0] || '',
        businessname: row[1] || '',
        businesstype: row[2] || '',
        businessdesc: row[3] || '',
      };
    }).filter(Boolean);
    for (const b of businesses) {
      await axios.post('http://localhost:8080/api/businesses', b);
    }
    await fetchList();
  };
  reader.readAsArrayBuffer(file);
}
</script>

<style scoped>
@import '../assets/style.css';
.page-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 16px; }
.data-table { width: 100%; border-collapse: collapse; background: #fff; }
.data-table th, .data-table td { border: 1px solid #eee; padding: 8px; }
.btn { background: #16a085; color: #fff; border: none; padding: 6px 16px; border-radius: 4px; cursor: pointer; margin-right: 8px; }
.search-input { padding: 6px 12px; border: 1px solid #ccc; border-radius: 4px;margin-top: 8px;  }
.modal { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.2); display: flex; align-items: center; justify-content: center; }
.modal-content { background: #fff; padding: 24px; border-radius: 8px; min-width: 300px; }
.modal-actions { margin-top: 16px; display: flex; gap: 12px; }
.action-cell { text-align: center; }
</style>